package com.atguigu.juc;

import java.util.concurrent.CountDownLatch;

//演示 CountDownLatch
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {

        // 主线程等待所有次线程执行完毕后，再执行主线程内容
//        mainAwait();

        // 多个线程都在等待，等主线程countDown时，所有线程同时执行
        allThreadStartSameTime();


    }

    private static void allThreadStartSameTime() throws InterruptedException {
        int threadNum = 10;
        CountDownLatch latch = new CountDownLatch(1);

        for(int i = 0; i < threadNum; i++) {
            TaskThread task = new TaskThread(latch);
            task.start();
        }

        Thread.sleep(1000);
        latch.countDown();

    }

    private static void mainAwait() throws InterruptedException {

        //创建CountDownLatch对象，设置初始值
        //6个同学陆续离开教室之后，班长锁门
        CountDownLatch countDownLatch = new CountDownLatch(6);

        //6个同学陆续离开教室之后
        for (int i = 1; i <=6; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+" 号同学离开了教室");

                //计数  -1
                countDownLatch.countDown();

            },String.valueOf(i)).start();
        }

        //等待
        countDownLatch.await();

        System.out.println(Thread.currentThread().getName()+" 班长锁门走人了");

    }


    static class TaskThread extends Thread {
        CountDownLatch latch;

        public TaskThread(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override
        public void run() {
            super.run();
            try {
                latch.await();
                System.out.println(getName() + " start " + System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}


